package com.ky.pro.java.sharding.ecommerce.config;

import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.injector.ISqlInjector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
@EnableConfigurationProperties(DynamicDataSourceProperties.class)
public class DynamicDataSourceConfiguration {

    @Autowired
    DynamicDataSourceProperties dynamicDataSourceProperties;

    @Bean("master")
    public DataSource getMaster() {
        return dynamicDataSourceProperties.getMaster();
    }

    @Bean("slave")
    public DataSource getSlave() {
        return dynamicDataSourceProperties.getSlave();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource master, DataSource slave) {
        Map<Object, Object> targetDataSources = new HashMap<>(5);
        targetDataSources.put(DataSourceNames.MASTER, master);
        targetDataSources.put(DataSourceNames.SLAVE, slave);
        return new DynamicDataSource(master, targetDataSources);
    }

    @Bean("batchSqlInjector")
    public BatchSqlInjector batchSqlInjector() {
        return new BatchSqlInjector();
    }

//    @Bean
//    public GlobalConfig globalConfig(@Qualifier("batchSqlInjector") ISqlInjector batchSqlInjector){
//        GlobalConfig globalConfig = new GlobalConfig();
//        globalConfig.setSqlInjector(batchSqlInjector);
//        return globalConfig;
//    }
}
